import { getMaxMinLngLat } from '@/utils/map/mapTool.js';
import MapFunc from '@/utils/map/leafletFunc.js';
const wellknown = require('wellknown');
import "leaflet-measure-path";
import "leaflet-measure-path/leaflet-measure-path.css";

export default {
  data() {
    return {
      MapFunc,
      // 绘图的变量
      overLayer: {
        polylines: [],
        polygons: [],
        measurements: []
      },
      tempGp: {
        lineNode: [],
        lineNodeLen: 0,
        tempLine: null,
        polygonNode: [],
        polygonNodeLen: 0,
        tempNode: [],
        tempPolygon: null,
        tempMeasure: null
      },
      editableRect: null,
    }
  },
  methods: {
    drawOn() {
      this.clearTemps();
      // 移除监听地图事件
      this.map.doubleClickZoom.disable();
      this.map.off('click');
      this.map.off('mousemove');
      this.map.off('dblclick');
    },
    drawOff() {
      // 移除监听地图点击事件
      this.map.off('click');
      this.map.off('mousemove');
      this.map.off('dblclick');
      this.map.doubleClickZoom.enable();
      // 复原鼠标平移样式
      MapFunc.removerCoursorStyle(this.map);
    },
    clearTemps() {
      // 清空面中间数据
      this.tempGp.polygonNode = [];
      this.tempGp.polygonNodeLen = 0;
      if (this.tempGp.tempPolygon) this.tempGp.tempPolygon.remove();

      // 清空线中间数据
      this.tempGp.lineNode = [];
      this.tempGp.lineNodeLen = 0;
      if (this.tempGp.tempLine) this.tempGp.tempLine.remove();
      this.tempGp.tempNode.map((el) => el.remove());
    },
    // 画线
    drawPolyline() {
      MapFunc.addCursorStyle(this.map, "crosshare-cursor");
      this.drawOn();

      let tempPolygonOpts = {
        color: "rgba(255, 0, 0, 0.85)",
        weight: 3,
        opacity: 0.85,
        // 添加量测信息属性，并开启
        showMeasurements: true,
        // 根据需要设置量测显示的参数
        measurementOptions: { minDistance: 500 }
      };

      let finalPolygonOpts = {
        color: "rgba(0, 255, 0, 0.85)",
        weight: 3,
        opacity: 0.85,
        // 同上
        // 添加量测信息属性，并开启
        showMeasurements: true,
        // 根据需要设置量测显示的参数
        measurementOptions: { minDistance: 500 }
      };
      this.map.on("click", evt => {
        this.tempGp.lineNode.push([evt.latlng.lat, evt.latlng.lng]);
        this.tempGp.tempNode.push(this.addNode(evt.latlng, this.map));
        this.tempGp.lineNodeLen = this.tempGp.lineNode.length;
      });

      this.map.on("mousemove", evt => {
        if (this.tempGp.lineNodeLen >= 1) {
          if (this.tempGp.tempLine) this.tempGp.tempLine.remove();
          this.tempGp.lineNode[this.tempGp.lineNodeLen] = [
            evt.latlng.lat,
            evt.latlng.lng
          ];

          this.tempGp.tempLine = MapFunc.createPolyline(
            this.map,
            this.tempGp.lineNode,
            tempPolygonOpts
          );
        }
      });

      this.map.on("dblclick", () => {
        let polyline = MapFunc.createPolyline(
          this.map,
          this.tempGp.lineNode,
          finalPolygonOpts
        );
        this.overLayer.polylines.push(polyline);
        this.clearTemps();
      });
    },
    // 画面
    drawPolygon(type, call) {
      MapFunc.addCursorStyle(this.map, 'crosshare-cursor');
      this.drawOn();

      let tempPolygonOpts = {
        color: 'rgba(0, 255, 0, 0.85)',
        weight: 3,
        opacity: 0.85,
        // 使用leaflet-measure-path测量
        showMeasurements: true,
        measurementOptions: { minDistance: 500 }
      };

      let finalPolygonOpts = {
        color: 'rgba(255, 0, 0, 0.85)',
        weight: 3,
        opacity: 0.85,
        // 使用leaflet-measure-path测量
        showMeasurements: true,
        measurementOptions: { minDistance: 500 }
      };

      this.map.on('click', (evt) => {
        this.tempGp.polygonNode.push([evt.latlng.lat, evt.latlng.lng]);
        this.tempGp.polygonNodeLen = this.tempGp.polygonNode.length;

        this.tempGp.tempNode.push(this.addNode(evt.latlng, this.map));
      });

      this.map.on('mousemove', (evt) => {
        if (this.tempGp.tempPolygon) this.tempGp.tempPolygon.remove();

        if (this.tempGp.polygonNodeLen == 1) {
          this.tempGp.polygonNode[this.tempGp.polygonNodeLen] = [evt.latlng.lat, evt.latlng.lng];
          this.tempGp.tempPolygon = MapFunc.createPolyline(this.map, this.tempGp.polygonNode, tempPolygonOpts);
        } else if (this.tempGp.polygonNodeLen >= 2) {
          this.tempGp.polygonNode[this.tempGp.polygonNodeLen] = [evt.latlng.lat, evt.latlng.lng];

          this.tempGp.tempPolygon = MapFunc.createPolygon(this.map, this.tempGp.polygonNode, tempPolygonOpts);
        }
      });

      this.map.on('dblclick', () => {
        console.log(this.tempGp.polygonNode);
        let polygon = MapFunc.createPolygon(this.map, this.tempGp.polygonNode, finalPolygonOpts);
        this.overLayer.measurements.push(polygon);
        this.map.fitBounds(polygon.getBounds())
        this.clearTemps();
        if (type === 'once') {
          this.drawOff();
          call && call(polygon)
        }
      });
    },
    addNode(latlng, map, draggable) {
      let node = MapFunc.createIcon({
        iconUrl: require('@/assets/image/map/node.png'),
        iconSize: [16, 16]
      });
      let marker = MapFunc.createMakerByLatlng(latlng, {
        icon: node,
        draggable
      });
      marker.addTo(map);
      return marker;
    },
    addAnchorPoint(latlng, map, draggable) {
      let node = MapFunc.createIcon({
        iconUrl: require('@/assets/image/map/node.png'),
        iconSize: [20, 20]
      });
      let marker = MapFunc.createMakerByLatlng(latlng, {
        icon: node,
        draggable
      });
      // 想标记置于所有其他标记（marker）之上，指定一个高值，如 1000。
      marker.setZIndexOffset(1000)
      this.anchorPointGroup.addLayer(marker)
      return marker;
    },
    addLabelbox(latlng, r = 1000) {
      let marker = L.marker(latlng, {
        icon: L.divIcon({
          html:
            '<div style="transform: translate(-35%, -30px);background-color: #fff;padding: 2px 5px;display: inline-block;white-space: nowrap;">' + Number(r).toFixed(0) + '米</div>'
        })
      });
      marker.setZIndexOffset(10)
      this.shapeGroup.addLayer(marker)
    },
    addEditableRect(latlng) {
      let rectLayer = L.rectangle(latlng);
      let finalRectL = rectLayer
      this.editableRect.addLayer(rectLayer);
      let latlng0 = latlng[0]
      let latlng1 = latlng[1]
      let marker = this.addAnchorPoint(latlng1, this.map, true)

      let gaplat = 0
      let gaplng = 0

      marker.on('drag', (e) => {
        let latlngx = e.latlng
        gaplat = latlngx.lat - latlng1[0]
        gaplng = latlngx.lng - latlng1[1]
        this.editableRect.clearLayers();
        let newRectLayer = L.rectangle([latlng0, [latlngx.lat, latlngx.lng]]);
        this.editableRect.addLayer(newRectLayer);
      })
      marker.on('dragend', (e) => {
        if ((gaplat < 0 && gaplng > 0) || (gaplat > 0 && gaplng < 0)) {
          marker.setLatLng(latlng1)
          this.editableRect.clearLayers();
          let newRectLayer = L.rectangle([latlng0, latlng1]);
          this.editableRect.addLayer(newRectLayer);
        } else {
          let curgap = gaplat > gaplng ? gaplat : gaplng
          let newlatlng1 = [latlng1[0] + curgap, latlng1[1] + curgap]
          let newlatlng0 = [latlng0[0] - curgap, latlng0[1] - curgap]
          this.editableRect.clearLayers();
          marker.setLatLng(newlatlng1);
          let newRectLayer = L.rectangle([newlatlng0, newlatlng1]);
          this.editableRect.addLayer(newRectLayer);
          latlng0 = newlatlng0
          latlng1 = newlatlng1
          finalRectL = newRectLayer
        }
      })
      return finalRectL
    },
    /**
     * 绘制可编辑的圆
     * @param {*} latlng ==> [latitude, longitude] [纬度, 经度]
     * @returns 
     */
    addEditableCircle(latlng, radius = 1000, call) {
      this.shapeGroup.clearLayers();
      this.anchorPointGroup.clearLayers();

      let circle = L.circle(latlng, { radius, color: '#fff', fillOpacity: 0, dashArray: '6 10', weight: 1 });
      this.shapeGroup.addLayer(circle);
      let finalCircleL = circle
      let latlngx = latlng
      let nwr = radius
      let originDistance = radius
      let maxLatlng = null
      let minmaxlatlng = getMaxMinLngLat(latlng[0], latlng[1], radius)
      let marker = this.addAnchorPoint([latlng[0], minmaxlatlng[1]], this.map, true)
      this.addLabelbox([latlng[0], minmaxlatlng[1]], nwr)

      let rPoint = [
        [minmaxlatlng[2], minmaxlatlng[0]],
        [minmaxlatlng[3], minmaxlatlng[1]]
      ];
      let rectL = L.rectangle(rPoint);
      this.shapeGroup.addLayer(rectL);

      let geoJSON = rectL.toGeoJSON();
      let wkt = wellknown.stringify(geoJSON);
      call && call({ latlng, radius: nwr, wkt })

      marker.on('drag', (e) => {
        console.log(e)
        this.shapeGroup.clearLayers();
        latlngx = e.latlng
        originDistance = this.map.distance(latlng, latlngx).toFixed(2);

        nwr = originDistance > 5000 ? 5000 : originDistance
        // if (originDistance > 5000) {
        //   console.log(originDistance)
        //   maxLatlng = latlngx
        //   marker.setLatLng(maxLatlng)
        //   console.log(latlngx)
        //   marker.setZIndexOffset(0)
        // }
        let newCircleLayer = L.circle(latlng, { radius: nwr, color: '#fff', fillOpacity: 0, dashArray: '6 10', weight: 1 });
        this.shapeGroup.addLayer(newCircleLayer);
        this.addLabelbox(latlngx, nwr);
        call && call({ latlng, radius: nwr })
      })
      marker.on('dragend', () => {
        if (originDistance > 5000) {
          nwr = 5000
          this.$message.warning('分析半径最大不能超过5000米');
        }
        let minaxlatng = getMaxMinLngLat(latlng[0], latlng[1], nwr)
        let rectPoint = [
          [minaxlatng[2], minaxlatng[0]],
          [minaxlatng[3], minaxlatng[1]]
        ];
        let rectLf = L.rectangle(rectPoint);
        finalCircleL = rectLf
        this.shapeGroup.addLayer(rectLf);

        let geoJSON = rectLf.toGeoJSON();
        let wktf = wellknown.stringify(geoJSON);
        call && call({ latlng, radius: nwr, wkt: wktf })
        this.$emit("dragend", { wkt: wktf, radius: nwr })
      })
      return finalCircleL
    }
  }
}